"""
配置文件管理
"""
import os
import json
from pathlib import Path
from typing import Dict, Any

class Config:
    """配置管理类"""
    
    def __init__(self):
        self.config_dir = Path("config")
        self.config_file = self.config_dir / "settings.json"
        self.accounts_file = self.config_dir / "accounts.json"
        
        # 确保配置目录存在
        self.config_dir.mkdir(exist_ok=True)
        
        # 默认配置
        self.default_config = {
            "browser": {
                "headless": False,
                "window_size": [1920, 1080],
                "user_agent": None
            },
            "monitor": {
                "interval": 5,
                "max_retries": 3,
                "timeout": 30
            },
            "ticket": {
                "auto_submit": True,
                "retry_count": 3,
                "retry_interval": 1
            },
            "notification": {
                "enabled": False,
                "webhook_url": None,
                "email": None
            }
        }
        
        self.config = self.load_config()
    
    def load_config(self) -> Dict[str, Any]:
        """加载配置"""
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                # 合并默认配置
                return {**self.default_config, **config}
            except:
                return self.default_config
        else:
            # 创建默认配置文件
            self.save_config(self.default_config)
            return self.default_config
    
    def save_config(self, config: Dict[str, Any] = None):
        """保存配置"""
        if config is None:
            config = self.config
        
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"保存配置失败: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        keys = key.split('.')
        config = self.config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
        self.save_config()
    
    def load_accounts(self) -> list:
        """加载保存的账号"""
        if self.accounts_file.exists():
            try:
                with open(self.accounts_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return []
        return []
    
    def save_accounts(self, accounts: list):
        """保存账号"""
        try:
            with open(self.accounts_file, 'w', encoding='utf-8') as f:
                json.dump(accounts, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"保存账号失败: {e}")

# 全局配置实例
config = Config()